package com.link2room.ironhide.facade.impl;

import com.link2room.common.constant.DefaultValue;
import com.link2room.common.dto.param.base.BaseL2rParamDto;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.jpa.result.QueryResult;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.ClassConverUtil;
import com.link2room.common.util.StringUtil;
import com.link2room.ironhide.dto.param.manager.ImageManagerParamDto;
import com.link2room.ironhide.dto.param.manager.ImageUploadParamDto;
import com.link2room.ironhide.dto.result.base.ImagesUploadResDto;
import com.link2room.ironhide.dto.result.base.L2RImgSourceDto;
import com.link2room.ironhide.entity.ImgRepertory;
import com.link2room.ironhide.facade.IimageFacadeService;
import com.link2room.ironhide.util.image.ImageUtil;
import com.link2room.ironhide.util.image.ImgCompress;
import com.link2room.ironhide.util.image.ImgCompressFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by LN on 2016/11/29.
 */
@Component("imageFacadeService")
public class ImageFacadeServiceImpl implements IimageFacadeService {
    @Resource
    private ImageUtil imageUtil;
    @Resource
    private ICommonService commonServiceSupport;

    @Override
    public QueryResult<L2RImgSourceDto> getImages(ImageManagerParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        String lhotelCode = paramDto.getLhotelCode();
        Integer currentPage = paramDto.getCurrentPage();
        Integer pageSize = paramDto.getPageSize();
        if(StringUtil.isBlank(lhotelGroupCode)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(),
                    BaseSysExceptionEnum.INVALID_PARA.getMsg()+"lhotelGroupCode is "+paramDto.getLhotelGroupCode(),
                    BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        if(StringUtil.isBlank(lhotelCode)){
            lhotelCode = DefaultValue.LHOTEL_CODE;
        }

        if(currentPage == null){
            currentPage = 1;
        }
        if(pageSize == null ){
            pageSize = 5;
        }

        ImgRepertory find = new ImgRepertory();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setLhotelCode(lhotelCode);
        QueryResult<ImgRepertory> queryRes = commonServiceSupport.findAllEQ(ImgRepertory.class, find, currentPage, pageSize);
        if(queryRes == null  || queryRes.getResultlist() ==null ){
            QueryResult<L2RImgSourceDto> res = new QueryResult<>();
            res.setTotalrecord(0);
            return res;
        }
        QueryResult<L2RImgSourceDto> res = new QueryResult<>();
        List<ImgRepertory> entityList = queryRes.getResultlist();
        List<L2RImgSourceDto> sourceDtolist = this.entityToImgDtoList(lhotelGroupCode,entityList);
        res.setResultlist(sourceDtolist);
        res.setTotalrecord(queryRes.getTotalrecord());
        res.setCurrentPage(queryRes.getCurrentPage());
        return res;
    }

    /**
     * entity转dtos
     * @param lhotelGroupCode
     * @param entityList
     * @return
     * @throws Exception
     */
    private List<L2RImgSourceDto> entityToImgDtoList(String lhotelGroupCode,List<ImgRepertory> entityList) throws Exception {
        String imgHostStr = getImgHost(lhotelGroupCode);
        return entityList.stream().map(entity -> entityToDto(entity, imgHostStr)).collect(Collectors.toList());
    }
    private String getImgHost(String lhotelGroupCode) throws Exception {
        return imageUtil.findImgHost(lhotelGroupCode);

    }
    private L2RImgSourceDto entityToDto (ImgRepertory entity,String imgHost){
        L2RImgSourceDto  dto = new L2RImgSourceDto();
        try {
            ClassConverUtil.copyProperties(entity,dto);
        } catch (Exception e) {
            throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION);
        }
        dto.setUrl(imgHost+dto.getUrl());
        return dto;
    }
    @Override
    public ImagesUploadResDto upload(ImageUploadParamDto paramDto) throws Exception {
       /* String ticket = paramDto.getTicket();
        if(StringUtil.isBlank(ticket) || "undefind".equals(paramDto.getTicket())){
            throw new SysException(SysExceptionEnum.INVALID_PARA.getCode(),
                    SysExceptionEnum.INVALID_PARA.getMsg()+"ticket is "+paramDto.getTicket(),
                    SysExceptionEnum.INVALID_PARA.getBizType());
        }*/
        MultipartFile file = paramDto.getFile();
        //get session
        BaseL2rParamDto sessionRq = new BaseL2rParamDto();
        sessionRq.setTicket(paramDto.getTicket());
        sessionRq.setOptId(paramDto.getOptId());
        //构建ImgCompress
        ImgCompress img = ImgCompressFactory.createImgCompress(file);
        String imgId = imageUtil.cacheImg(img);
        ImagesUploadResDto res = new ImagesUploadResDto();
        res.setImgId(imgId);
        return res;
    }

    @Override
    public List<L2RImgSourceDto> saveImages(ImageManagerParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        String lhotelCode = paramDto.getLhotelCode();
        List<L2RImgSourceDto> imgeSources = paramDto.getImgSources();
        if(StringUtil.isBlank(lhotelGroupCode)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(),
                    BaseSysExceptionEnum.INVALID_PARA.getMsg()+"lhotelGroupCode is "+paramDto.getLhotelGroupCode(),
                    BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        if(StringUtil.isBlank(lhotelCode)){
            lhotelCode = DefaultValue.LHOTEL_CODE;
        }
        if(imgeSources == null || imgeSources.isEmpty()){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(),
                    BaseSysExceptionEnum.INVALID_PARA.getMsg()+"imgeSources is empty",
                    BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }

        List<ImgRepertory> imgEntitys = new ArrayList<>();
        List<L2RImgSourceDto> imgDtos = getImgsFromCache(imgeSources);
        List<L2RImgSourceDto> sourceDtolist = new ArrayList<>();
        String imgHost = getImgHost(lhotelGroupCode);
        //图片持久化
        for (L2RImgSourceDto dto:imgDtos) {
            String filePath = "";
            ImageUtil.Img imgDto = imageUtil.imgePersistence(lhotelGroupCode, lhotelCode, dto);
            if(imgDto != null){
                filePath = imgDto.getRelativePath();
            }
            ImgRepertory img = new ImgRepertory();
            img.setUrl(filePath);
            img.setLhotelGroupCode(lhotelGroupCode);
            img.setLhotelCode(lhotelCode);
            img.setRemak(dto.getRemak());
            img.setHashCode(dto.getImgCompress().getImageFileHashCode());
            img.setImgCode(imgDto.getFileCode());
            imgEntitys.add(img);
            L2RImgSourceDto sDto = entityToDto(img, imgHost);
            sDto.setImgId(dto.getImgId());
            sourceDtolist.add(sDto);
        }
        commonServiceSupport.saveList(imgEntitys);

//        List<L2RImgSourceDto> sourceDtolist = this.entityToImgDtoList(lhotelGroupCode,imgEntitys);
        return sourceDtolist;
    }

    /**
     * 从缓存中取出图片
     * @param imgeSources
     * @return
     */
    private List<L2RImgSourceDto> getImgsFromCache(List<L2RImgSourceDto> imgeSources){
        if(imgeSources == null || imgeSources.isEmpty()){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(),
                    BaseSysExceptionEnum.INVALID_PARA.getMsg()+"imgeSources is empty",
                    BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        Iterator<L2RImgSourceDto> it = imgeSources.iterator();

        while (it.hasNext()){
            L2RImgSourceDto dto = it.next();
            ImgCompress image = imageUtil.getImages(dto.getImgId());
            if(image != null){
                dto.setImgCompress(image);
            }else{
                it.remove();
            }
        }
        return imgeSources;
    }
}
